package com.smt.modules.bus.service.impl;

import com.smt.common.enums.Code;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.common.utils.R;
import com.smt.modules.app.utils.FileSizeUtil;
import com.smt.modules.bus.entity.DocumentEntity;
import com.smt.modules.bus.service.DocumentService;
import com.smt.modules.bus.vo.AttachmentVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smt.common.utils.PageUtils;
import com.smt.common.utils.Query;

import com.smt.modules.bus.dao.AttachmentDao;
import com.smt.modules.bus.entity.AttachmentEntity;
import com.smt.modules.bus.service.AttachmentService;


@Service("attachmentService")
public class AttachmentServiceImpl extends ServiceImpl<AttachmentDao, AttachmentEntity> implements AttachmentService {
    public static final String KB = "KB";
    public static final String MB = "MB";
    public static final long MAX_MB = 1024*1024;
    @Autowired
    private DocumentService documentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<AttachmentEntity> page = this.selectPage(
                new Query<AttachmentEntity>(params).getPage(),
                new EntityWrapper<AttachmentEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取当前团队下的文件列表
     *
     * @param projectId
     * @return
     */
    @Override
    public R list(Long projectId) {
        List<AttachmentEntity> attachmentEntities = selectList(new EntityWrapper<AttachmentEntity>()
                .eq("project_id", projectId)
                .eq("is_public", 1)
                .eq("is_delete", 0));
        List<DocumentEntity> documentEntities = documentService.selectList(new EntityWrapper<DocumentEntity>()
                .eq("project_id", projectId)
                .in("status", "0,1,3"));
        return R.ok().put("attachments",attachmentEntities).put("documents",documentEntities);
    }

    /**
     * 保存文件 TODO
     *
     * @param attachment
     * @param userId
     * @return
     */
    @Override
    public R save(AttachmentVo attachment,Long userId) {
        //查询重复文件
        Long projectTaskId = attachment.getProjectTaskId();
        Long projectSubTaskId = attachment.getProjectSubTaskId();
        EntityWrapper<AttachmentEntity> entityWrapper = new EntityWrapper<>();
        if(projectSubTaskId != null){
            entityWrapper.eq("project_task_id",projectSubTaskId);
        }else if(projectTaskId != null){
            entityWrapper.eq("project_sub_task_id",projectTaskId);
        }
        attachment.setUploadedId(userId);
        String url = attachment.getUrl();
        if(url == null || "".equals(url)){
            return R.error(EnumToKeyUtil.toInt(Code.REQUEST_PARAM_EMPTY),"文件路径为空");
        }
        String fileName = url.substring(url.lastIndexOf(File.separator)+1, url.length());
        attachment.setFileName(fileName);
        attachment.setCreateTime(DateTime.now().toDate());
        attachment.setUpdateTime(DateTime.now().toDate());
        AttachmentEntity attachmentEntity = attachment.copyPropertiesTo(new AttachmentEntity());
        double fileSizeToNumber = FileSizeUtil.getFileSizeToNumber(attachment.getUrl());
        attachment.setFileSize(fileSizeToNumber);
        //覆盖文件记录(多次上传覆盖源文件记录)
        int count = selectCount(entityWrapper);
        boolean insert;
        if(count != 0) {
            AttachmentEntity attachmentE = attachment.copyPropertiesTo(new AttachmentEntity());
            attachmentE.setStatus(0);
            insert = updateById(attachmentE);
        }else{
            attachmentEntity.setStatus(0);
            insert = insert(attachmentEntity);
        }
        return insert?R.ok("保存文件成功"):
                R.error(EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR),"保存文件失败");
    }
}
